package kr.saeildamil.androidStudy_second.brservice;

import kr.saeildamil.androidStudy_second.R;
import kr.saeildamil.androidStudy_second.brservice.LocalService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;

public class BoundServiceTest extends Activity {
	LocalService mService;
	boolean mBound;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29and30_boundservicetest);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, LocalService.class);
		bindService(intent, mConn, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		super.onStop();
		if(mBound){
			unbindService(mConn);
		}
	}

	@Override
	protected void onResume() {
		super.onStart();
		Intent intent = new Intent(this, LocalService.class);
		bindService(intent, mConn, Context.BIND_AUTO_CREATE);
	}



	ServiceConnection mConn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
		}
	};

	public void mOnClick(View v) {
		if(mBound){
			int num = mService.getRandomNumber();
			Toast.makeText(this, "Number:"+ num, Toast.LENGTH_SHORT).show();
		}
	}
}
